package com.runtime.dao.impl;


import com.runtime.bean.UserEntry;
import com.runtime.common.DBUtil;
import com.runtime.dao.UserDao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    DBUtil dbUtil = new DBUtil();

    @Override
    public List<UserEntry> getUserList() {
        String sql = "select * from t_stu";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<UserEntry> list = new ArrayList<>();
        try {
            preparedStatement = dbUtil.getConn().prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                char sex = resultSet.getString("sex").charAt(0);
                UserEntry userEntry = new UserEntry(id,name,sex,age);
                list.add(userEntry);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbUtil.close(preparedStatement,resultSet);
        }
        return list;
    }

    @Override
    public boolean addUser(UserEntry entry) {
        String sql = "insert into t_stu values(?,?,?,?)";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = dbUtil.getConn().prepareStatement(sql);
            preparedStatement.setInt(1,entry.getId());
            preparedStatement.setString(2,entry.getName());
            preparedStatement.setInt(3,entry.getAge());
            preparedStatement.setString(4,entry.getSex()+"");
            int num = preparedStatement.executeUpdate();
            return num>0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dbUtil.close(preparedStatement,null);
        }
        return false;
    }

    public boolean deleteUser(UserEntry entry) {
        return false;
    }

    @Override
    public boolean updateUser(UserEntry entry) {
        return false;
    }
}
